/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.classes.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.api.vo.UserDeptModel;
import org.springblade.modules.classes.bo.UserBindingBo;
import org.springblade.modules.classes.entity.ClassesUserEntity;
import org.springblade.modules.classes.entity.UserBindingEntity;
import org.springblade.modules.classes.service.IClassesUserService;
import org.springblade.modules.classes.vo.UserBindingVO;
import org.springblade.modules.classes.excel.UserBindingExcel;
import org.springblade.modules.classes.mapper.UserBindingMapper;
import org.springblade.modules.classes.service.IUserBindingService;
import org.springblade.modules.library.entity.AllowUserEntity;
import org.springblade.modules.library.service.IAllowUserService;
import org.springblade.modules.material.entity.PaperReleaseEntity;
import org.springblade.modules.material.entity.ReleaseExamUserEntity;
import org.springblade.modules.material.entity.TrainArchiveUserEntity;
import org.springblade.modules.material.service.IPaperReleaseService;
import org.springblade.modules.material.service.IReleaseExamUserService;
import org.springblade.modules.material.service.ITrainArchiveUserService;
import org.springblade.modules.personal.entity.UserBaseEntity;
import org.springblade.modules.personal.service.IUserBaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 推送用户表 服务实现类
 *
 * @author junxin
 * @since 2023-07-10
 */
@Service
@AllArgsConstructor
public class UserBindingServiceImpl extends BaseServiceImpl<UserBindingMapper, UserBindingEntity> implements IUserBindingService {
	private final IClassesUserService classesUserService;
	private final IUserBaseService userBaseService;
	private final IReleaseExamUserService releaseExamUserService;
	private final IPaperReleaseService paperReleaseService;
	private final ITrainArchiveUserService archiveUserService;
	private final IAllowUserService allowUserService;


	@Override
	public IPage<UserBindingVO> selectUserBindingPage(IPage<UserBindingVO> page, UserBindingVO userBinding) {
		return page.setRecords(baseMapper.selectUserBindingPage(page, userBinding));
	}


	@Override
	public List<UserBindingExcel> exportUserBinding(Wrapper<UserBindingEntity> queryWrapper) {
		List<UserBindingExcel> userBindingList = baseMapper.exportUserBinding(queryWrapper);
		//userBindingList.forEach(userBinding -> {
		//	userBinding.setTypeName(DictCache.getValue(DictEnum.YES_NO, UserBinding.getType()));
		//});
		return userBindingList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addUserBinding(UserBindingBo bo) {

		Set<Long> userIdList = new HashSet<>();

		//1.部门链表处理  部门id集
		if (CollectionUtils.isNotEmpty(bo.getDeptList())) {
			List<UserBaseEntity> userListByDept = userBaseService.list(Wrappers.<UserBaseEntity>query()
				.lambda().in(UserBaseEntity::getDeptId, bo.getDeptList()));

			if (CollectionUtils.isNotEmpty(userListByDept)) {
				userIdList.addAll(userListByDept.stream().map(UserBaseEntity::getUserId).collect(Collectors.toList()));
			}
		}

		//2.导入的用户链表处理  身份证集
		if (CollectionUtils.isNotEmpty(bo.getImportList())) {
			List<UserBaseEntity> userListByIdcard = userBaseService.list(Wrappers.<UserBaseEntity>query()
				.lambda().in(UserBaseEntity::getIdCard, bo.getImportList()));
			if (CollectionUtils.isNotEmpty(userListByIdcard)) {
				userIdList.addAll(userListByIdcard.stream().map(UserBaseEntity::getUserId).collect(Collectors.toList()));
			}
		}

		//3.选中的用户列表处理  userId集
		if (CollectionUtils.isNotEmpty(bo.getSelectedList())) {
			userIdList.addAll(bo.getSelectedList());
		}

		//4.选中的班级列表处理  classesId集
		if (CollectionUtils.isNotEmpty(bo.getClassesList())) {
			List<ClassesUserEntity> classesUserList = classesUserService.list(Wrappers.<ClassesUserEntity>query().lambda().in(ClassesUserEntity::getClassesId, bo.getClassesList()));
			userIdList.addAll(classesUserList.stream().map(ClassesUserEntity::getUserId).collect(Collectors.toList()));
		}

		if (1 == bo.getType()) { //班级学员处理
			List<ClassesUserEntity> classesUserEntityList = userIdList.stream().map(userId -> {
				ClassesUserEntity po = new ClassesUserEntity();
				po.setUserId(userId);
				po.setClassesId(bo.getBindingId());
				return po;
			}).collect(Collectors.toList());
			classesUserService.remove(Wrappers.<ClassesUserEntity>query().lambda().eq(ClassesUserEntity::getClassesId,bo.getBindingId()));
			classesUserService.saveBatch(classesUserEntityList);
		}

		if (2 == bo.getType()) { //考试学员处理
			PaperReleaseEntity paperReleaseEntity = paperReleaseService.getById(bo.getBindingId());
			int permit=1;//考试权限
			if (paperReleaseEntity.getPermit()==1)permit=0;//表示需要特定场所考试，需要老师授权才能进入考试
			int finalPermit = permit;

			//获取旧数据
			List<ReleaseExamUserEntity> oldUserList = releaseExamUserService.list(Wrappers.<ReleaseExamUserEntity>query().lambda()
				.eq(ReleaseExamUserEntity::getReleaseId, bo.getBindingId()));

			//旧数据叠加到新数据上
			if (CollectionUtils.isNotEmpty(oldUserList))userIdList.addAll(oldUserList.stream().map(ReleaseExamUserEntity::getUserId).collect(Collectors.toSet()));


			List<ReleaseExamUserEntity> releaseExamUserList = userIdList.stream().map(userId -> {
				ReleaseExamUserEntity po = new ReleaseExamUserEntity();
				po.setUserId(userId);
				po.setPermit(finalPermit);
				po.setReleaseId(bo.getBindingId());
				return po;
			}).collect(Collectors.toList());

			releaseExamUserService.remove(Wrappers.<ReleaseExamUserEntity>query().lambda().eq(ReleaseExamUserEntity::getReleaseId,bo.getBindingId()));
			releaseExamUserService.saveBatch(releaseExamUserList);
		}

		if (3 == bo.getType()) { //线下实训人员处理
			List<TrainArchiveUserEntity> userEntityList = userIdList.stream().map(userId -> {
				TrainArchiveUserEntity po = new TrainArchiveUserEntity();
				po.setUserId(userId);
				po.setArchiveId(bo.getBindingId());
				return po;
			}).collect(Collectors.toList());
			archiveUserService.remove(Wrappers.<TrainArchiveUserEntity>query().lambda().eq(TrainArchiveUserEntity::getArchiveId,bo.getBindingId()));
			archiveUserService.saveBatch(userEntityList);
		}

		if (4 == bo.getType()) { //允许查看资料的用户
			List<AllowUserEntity> userEntityList = userIdList.stream().map(userId -> {
				AllowUserEntity po = new AllowUserEntity();
				po.setAllowUserId(userId);
				po.setDataShareId(bo.getBindingId());
				return po;
			}).collect(Collectors.toList());
			allowUserService.remove(Wrappers.<AllowUserEntity>query().lambda().eq(AllowUserEntity::getDataShareId,bo.getBindingId()));
			allowUserService.saveBatch(userEntityList);
		}
	}

}
